<template>
  <div class="page" @scroll="paperScroll" ref="page">
    <div class="head">
      <h1>{{ $t('我的小猴') }}</h1>
      <div class="btns">
        <div class="option" @click="showFilter = true"></div>
      </div>
    </div>
    <sticky>
      <div class="filter">
        <ul class="status">
          <li v-for="(item, index) in category" :class="{'active': item.value == params.status}" @click="changeCategory(item.value)" :key="index">{{$t(item.name)}}</li>
        </ul>
        <ul class="order" v-show="params.status != 5">
          <li :class="{'active': item.value == params.orderBy,'up': params.sort == 0}" @click="changeOrder(item.value)" v-for="(item, index) in order" :key="index">{{$t(item.name)}}</li>
        </ul>
      </div>
    </sticky>
    <div class="records" v-if="params.status == 5">
      <div class="tab">
        <div :class="{'active': activeRecord == 1}" @click="changeHistory(1)">{{ $t('交易记录') }}</div>
        <div :class="{'active': activeRecord == 0}" @click="changeHistory(0)">{{ $t('生育记录') }}</div>
      </div>
      <empty v-if="historyList.length == 0"></empty>
      <!-- 历史记录 -->
      <div class="panel" v-for="(item,index) in historyList" :key="index">
        <router-link tag="div" class="record-item" :to="'/monkey/'+ item.mid">
          <div class="img">
            <img :src="item.facade" :style="{background: item.background}" alt="">
          </div>
          <div class="info">
            <div>
              <span class="id">{{ item | tradeType }}</span>
              <span class="status" :style="{color: statusColor(item.status)}">{{ item.status | tradeStatus }}</span>
            </div>
            <div>
              <span class="cost">{{ $t('价格') }}：{{ item.coin }}猴毛</span>
              <span class="date">{{ item.updateTime | formatTime }}</span>
            </div>
          </div>
        </router-link>
      </div>
      <div class="load" v-show="loadMore0 && activeRecord == 0" @click="more(activeRecord)">加载更多</div>
      <div class="load" v-show="loadMore1 && activeRecord == 1" @click="more(activeRecord)">加载更多</div>
    </div>
    <!-- 我的猴子 -->
    <div class="monkeys" v-else>
      <box gap="12px" v-if="homeList.length > 0 && params.status == ''">
        <x-button @click.native="feedAllConfirm()" style="background: #8ca1ca;color: #fff">一键喂食</x-button>
      </box>
      <div class="panel" v-for="(item,index) in homeList" :key="index">
        <div class="list-item" @click="toMonkey(item.id)">
          <div class="img">
            <img :src="item.facade" :style="{background: item.background}" alt="">
            <div class="id"># {{ item.id }}</div>
            <div class="info">
              <p>{{ item.bearNum }} {{ $t('次') }}</p>
              <p><span>{{ item.grow | toFix(2) }}/</span><span>{{ item.bear | toFix(2) }}/</span><span>{{ item.makeMoney | toFix(2) }}</span></p>
            </div>
          </div>
          <ul class="minfo">
            <li>{{ item.generation }} {{ $t('代') }} · {{ item.weight | toFix(2) }} kg</li>
            <li>
              <span>{{ $t('投食进度') }}: </span>
              <div class="progress">
                <div class="percent yellow" :style="{width: item.growIng / item.growLimit * 100 + '%' }"></div>
              </div>
            </li>
            <li>
              <span>状态：</span>
              <span>{{monkeyStatus[item.status]}}</span>
            </li>
            <li>
              <span>{{ $t('下次生育') }}:</span>
              <count-down :startTime="new Date().getTime()" :endTime="item.nextBearDate" endText="准备就绪"></count-down>
            </li>
          </ul>
          <div class="tag" v-if="item.type > 0">
            <i class="ico" :class="{'sell':item.type == 1,'love':item.type == 2}"></i>
            <span>{{ item.price }}</span>
          </div>
        </div>
      </div>
      <infinite-loading @infinite="initData" ref="infiniteLoading">
        <span slot="no-more"></span>
        <div slot="no-results" v-if="params.status != ''">
          <br>
          <empty></empty>
        </div>
        <div slot="no-results" v-else></div>
        <spinner slot="spinner" type="lines"></spinner>
      </infinite-loading>
    </div>
    <div class="panel" v-if="recommendList.length > 0 && showRecommend && params.status == ''">
      <div class="nomonkey">
        <h3>哦哟<br>看起来你还没有任何猴子哦~</h3>
        <span>这些看起来还不错</span>
      </div>
      <div class="find-list">
        <router-link tag="div" class="item" :to="`/monkey/${item.id}`" v-for="(item,index) in recommendList" :key="index">
          <div class="img">
            <img :src="item.facade" :style="{background: item.background}">
            <div class="id"># {{ item.id }}</div>
            <div class="info">
              <p>{{ item.generation }}代</p>
              <p>{{ item.grow }}/{{ item.bear }}/{{ item.makeMoney }} · {{ item.weight }} kg</p>
            </div>
          </div>
          <div class="price">
            <span>{{ item.price }} 猴毛</span>
          </div>
        </router-link>
      </div>
      <div class="link">
        <router-link to="/market">发现更多>></router-link>
      </div>
    </div>
    <lottery v-if="showRecommend && params.status == ''"></lottery>
    <!-- 复杂筛选 -->
    <div v-transfer-dom>
      <popup v-model="showFilter" position="right" width="300px" class="filters">
        <div class="wrap">
          <div class="block">
            <group :title="$t('代数')" class="input-range">
              <x-input v-model="params.startGen" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endGen" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
            <group :title="$t('体重')" class="input-range">
              <x-input v-model="params.startWeight" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endWeight" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
            <group :title="$t('生育次数')" class="input-range">
              <x-input v-model="params.startBearNum" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endBearNum" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
            <group :title="$t('成长值')" class="input-range">
              <x-input v-model="params.startGrow" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endGrow" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
            <group :title="$t('生育值')" class="input-range">
              <x-input v-model="params.startBear" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endBear" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
            <group :title="$t('力量值')" class="input-range">
              <x-input v-model="params.startMakeMoney" type="number" novalidate :placeholder="$t('最低')"></x-input>
              <div class="dash"></div>
              <x-input v-model="params.endMakeMoney" type="number" novalidate :placeholder="$t('最高')"></x-input>
            </group>
          </div>
        </div>
        <div class="button">
          <x-button type="warn" class="btn" @click.native="resetFilter">{{$t('重置')}}</x-button>
          <x-button type="primary" class="btn" @click.native="enterFilter">{{$t('确定')}}</x-button>
        </div>
      </popup>
    </div>
  </div>
</template>

<i18n>
首页:
  en: Home
全部:
  en: All
集市:
  en: Market
鹊桥:
  en: Sire
历史:
  en: Records
代数:
  en: Gen
代:
  en: Gen
次:
  en: times
体重:
  en: Weight
收益:
  en: Income
投食进度:
  en: Feeding progress
昨日掘金:
  en: Yesterday income
不可生育:
  en: Sterilization
生育记录:
  en: birth records
交易记录:
  en: trade records
下次生育:
  en: Next birth
已复制:
  en: Copied
</i18n>

<script>
  import {
    Group,
    XInput,
    Sticky,
    TransferDom,
    Spinner,
    Popup,
    XButton,
    Box
  } from 'vux'
  import lottery from './common/lottery.vue'
  import empty from './common/empty.vue'
  import CountDown from './common/vue2-countdown.vue'
  import InfiniteLoading from 'vue-infinite-loading';
  export default {
    directives: {
      TransferDom
    },
    components: {
      Group,
      XInput,
      lottery,
      Sticky,
      empty,
      CountDown,
      InfiniteLoading,
      Spinner,
      Popup,
      XButton,
      Box
    },
    data() {
      return {
        category: [{
            name: '全部',
            value: ''
          },
          {
            name: '集市',
            value: '1'
          },
          {
            name: '鹊桥',
            value: '2'
          },
          {
            name: '战斗',
            value: '3'
          },
          {
            name: '采集',
            value: '4'
          },
          {
            name: '空闲',
            value: '0'
          },
          {
            name: '历史',
            value: '5'
          },
        ],
        order: [{
            name: '代数',
            value: '1'
          },
          {
            name: '体重',
            value: '2'
          }
        ],
        homeList: [],
        params: {
          orderBy: '1', //1:代数,2:体重,3:收益
          sort: '0', //0:升 1:降
          status: '', //0:正常 1: 出售 2:繁殖,不传值显示全部
          current: 1,
          startGen: '',
          endGen: '',
          startGrow: '',
          endGrow: '',
          startBear: '',
          endBear: '',
          startMakeMoney: '',
          endMakeMoney: '',
          startBearNum: '',
          endBearNum: '',
          startWeight: '',
          endWeight: '',
        },
        showFilter: false,
        recommendList: [],
        historyList: [],
        showRecommend: false,
        activeRecord: 1,
        buyCurrent: 1,
        breedCurrent: 1,
        buyHistoryList: [],
        breedHistoryList: [],
        loadMore0: false,
        loadMore1: false,
        scrollTop_home: 0,
        monkeyStatus: ['空闲','出售中','生育挂单','参战中','采集中']
      }
    },
    mounted() {
      this.$nextTick(function() {
        // console.log(new WebSocket('wss://echo.websocket.org'))
      });
    },
    activated() {
      this.$refs.page.scrollTop = this.$store.state.scrollTop_home;
    },
    methods: {
      initData($state) {
        this.$http
          .post(`/game/v2/myMonkeyPage`, this.params)
          .then(res => {
            if (res.code == 200) {
              if (res.result.total > 0) {
                this.showRecommend = false
                this.homeList = this.homeList.concat(res.result.records);
                $state.loaded();
                if (res.result.current < res.result.pages) {
                  this.params.current += 1;
                } else {
                  $state.complete();
                }
              } else {
                this.showRecommend = true
                this.getRecommend()
                $state.complete();
              }
            } else {
              this.$vux.toast.text(res.msg)
            }
          })
          .catch(function(error) {});
      },
      getRecommend() {
        if (this.showRecommend && this.params.status == '') {
          this.$http
            .get(`/game/recentlyThree`)
            .then(res => {
              if (res.code == 200) {
                this.recommendList = res.result;
              } else {}
            })
            .catch(function(error) {});
        }
      },
      feedAllConfirm() {
        var that = this;
        this.$vux.confirm.show({
          title: '提示',
          content: `使用此功能需要绑定瑞波钱包地址，每只小猴收取5猴毛服务费！注意半个小时仅能使用一次此功能。`,
          confirmText: '一键喂食',
          cancleText: '算了',
          onConfirm() {
            that.feedAll()
          }
        })
      },
      feedAll() {
        this.$vux.loading.show({
          text: '请稍后'
        })
        this.$http
          .post(`gameCastle/v2/automaticFeed`,this.params).then(res => {
            this.$vux.loading.hide()
            
            if (res.code == 200) {
              this.$vux.toast.text('一键喂食任务提交成功，请耐心等待。')
            } else {
              this.$vux.toast.text(res.msg)
            }
          })
          .catch(function(error) {});
      },
      changeHistory(index) {
        this.activeRecord = index;
        if (index == 0) {
          this.historyList = this.breedHistoryList
        } else {
          this.historyList = this.buyHistoryList
        }
      },

      resetFilter() {
        this.params.startGen = '';
        this.params.endGen = '';
        this.params.startGrow = '';
        this.params.endGrow = '';
        this.params.startBear = '';
        this.params.endBear = '';
        this.params.startMakeMoney = '';
        this.params.endMakeMoney = '';
        this.params.startBearNum = '';
        this.params.endBearNum = '';
        this.params.startWeight = '';
        this.params.endWeight = '';
      },
      enterFilter() {
        this.$nextTick(() => {
          this.resetData()
          this.showFilter = false
        });
      },
      resetData() {
        this.params.current = 1;
        this.homeList = []
        this.$refs.infiniteLoading.$emit('$InfiniteLoading:reset');
      },
      paperScroll(e) {
        this.scrollTop_home = e.srcElement.scrollTop
      },
      toMonkey(id) {
        this.$store.commit('scrollTop', {
          name: 'scrollTop_home',
          value: this.scrollTop_home
        })
        this.$router.push(`/monkey/${id}`)
      },
      more(index) {
        if (index == 0) {
          this.breedCurrent += 1;
          this.getBreedHistory()
        } else {
          this.buyCurrent += 1;
          this.getBuyHistory()
        }
      },
      getBuyHistory() {
        this.$http
          .post(`/game/monkeyBuyPage`, {
            current: this.buyCurrent
          })
          .then(res => {
            if (res.code == 200) {
              if (res.result.total > 0) {
                this.buyHistoryList = this.buyHistoryList.concat(res.result.records);
                if (this.activeRecord == 1) {
                  this.historyList = this.buyHistoryList
                }
                if (res.result.current < res.result.pages) {
                  this.loadMore1 = true
                } else {
                  this.loadMore1 = false
                }
              } else {}
            } else {}
          })
          .catch(function(error) {});
      },
      getBreedHistory() {
        this.$http
          .post(`/game/monkeyBearPage`, {
            current: this.breedCurrent
          })
          .then(res => {
            if (res.code == 200) {
              if (res.result.total > 0) {
                this.breedHistoryList = this.breedHistoryList.concat(res.result.records);
                if (this.activeRecord == 0) {
                  this.historyList = this.breedHistoryList
                }
                if (res.result.current < res.result.pages) {
                  this.loadMore0 = true
                } else {
                  this.loadMore0 = false
                }
              } else {}
            } else {}
          })
          .catch(function(error) {});
      },
      // 筛选目录
      changeCategory(value) {
        this.params.status = value
        if (value == 5) {
          this.breedCurrent = 1
          this.buyCurrent = 1;
          this.breedHistoryList = [];
          this.buyHistoryList = [];
          this.getBreedHistory()
          this.getBuyHistory()
        } else {
          this.$nextTick(() => {
            this.resetData()
          });
        }
      },
      changeOrder(order) {
        //点击同一个
        if (order == this.params.orderBy) {
          this.params.sort = this.params.sort == 0 ? 1 : 0;
        } else {
          this.params.orderBy = order;
          this.params.sort = 1
        }
        this.resetData()
      },
      statusColor(status) {
        var str = '';
        var color = '';
        switch (status) {
          case 0:
            str = '已挂单'
            color = '#0579c1'
            break;
          case 1:
            str = '等待付款'
            color = '#e64340'
            break;
          case 2:
            str = '等待确认'
            color = '#ed8422'
            break;
          case 3:
            str = '已完成'
            color = '#1aad19'
            break;
          case -1:
            str = '已取消'
            color = '#d9dbee'
            break;
        }
        return color
      }
    }
  }
</script>

<style lang="scss" scoped>

  .head {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .btns{
      display: flex;
      align-items: center;
      a {
        display: inline-block;
        padding: 2px 5px;
        border: 1px solid $tmdark;
        border-radius: 5px;
        font-size: 12px;
        color: $tmdark;
      }
    }
    .option {
      width: 28px;
      height: 28px;
      margin-left: 5px;
      background: url() no-repeat 50%;
      background-size: 16px 16px;
    }
  }
  .filter {
    display: flex;
    justify-content: space-between;
    white-space: nowrap; // flex-wrap: wrap;
    font-size: 12px;
    background: #fff;
    height: 40px;
    line-height: 40px;
    padding: 0 12px;
    margin: 0 8px 12px;
    border-radius: 4px;
    box-shadow: 3px 3px 10px 0px rgba(158, 158, 158, 0.4);
    overflow-x: scroll;
    overflow-y: hidden;
    &::-webkit-scrollbar {
      display: none;
    }
    ul {
      display: flex;
      align-items: center;
      li {
        cursor: pointer;
      }
    }
    .status {
      color: $grey;
      li {
        transition: all .3s;
      }
      li:not(:last-child) {
        margin-right: 12px;
      }
      .active {
        color: $green;
        font-size: 14px;
        border-bottom: 2px solid $green;
      }
    }
    .order {
      color: $link;
      margin-left: 20px;
      li+li {
        margin-left: 12px;
      }
      .active:after {
        content: '';
        display: inline-block;
        vertical-align: middle;
        margin-top: -2px;
        width: 12px;
        height: 12px;
        background: url() no-repeat 50%;
        background-size: cover;
      }
      .active.up:after {
        transform: rotate(-180deg)
      }
    }
  }
  .list-item {
    position: relative;
    display: flex;
    height: 100px;
    overflow: hidden;
    .img {
      width: 100px;
      height: 100px;
      font-weight: 300;
      margin-right: 10px;
      position: relative;
      flex-shrink: 0;
      font-size: 10px;
      border-radius: 4px;
      overflow: hidden;
      @media only screen and (min-width: 375px) {
        font-size: 10px;
      }
      @media only screen and (min-width: 414px) {
        font-size: 12px;
      }
      @media only screen and (min-width: 768px) {
        font-size: 14px;
      }
      .id {
        position: absolute;
        color: $grey;
        background-color: rgba(255, 255, 255, .8);
        left: 0;
        top: 6px;
        padding: 0 5px 0 0;
        border-radius: 0 100px 100px 0;
      }
      img {
        width: 100%;
      }
      .info {
        position: absolute;
        left: 2px;
        bottom: 2px;
        line-height: 14px;
        color: #000;
        width: 100%;
        white-space: nowrap;
        padding: 2px;
        p {
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
    }
    .minfo {
      display: flex;
      justify-content: space-between;
      flex-direction: column;
      font-size: 14px;
      color: $grey;
      white-space: nowrap;
      li:first-child {
        color: #000;
      }
      span {
        vertical-align: middle;
      }
      .progress {
        display: inline-block;
        width: 80px;
        height: 17px;
        border: 1px solid #e8e3e3;
        vertical-align: middle;
        overflow: hidden;
        border-radius: 2px;
        .percent {
          font-size: 12px;
          line-height: 15px;
        }
        .yellow {
          background-color: rgba(3, 169, 244, 0.34);
          height: 100%;
        }
      }
    }
    .tag {
      position: absolute;
      top: -3px;
      right: 0;
      color: $green;
    }
  }
  .find-list {
    // position: absolute;
    // left: 0;
    text-align: center;
    .item {
      display: inline-block;
      vertical-align: middle;
      width: 33.33%; // min-height: 150px;
      border: 4px solid transparent;
      line-height: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      .img {
        position: relative;
        img {
          width: 100%;
          background-color: #e0e2ff;
        }
        .id {
          position: absolute;
          color: $grey;
          background-color: #fff;
          left: 0;
          top: 6px;
          font-size: 10px;
          padding: 3px 5px 3px 0;
          border-radius: 0 10px 10px 0;
        }
        .info {
          font-size: 10px;
          position: absolute;
          width: 100%;
          overflow: hidden;
          text-overflow: ellipsis;
          left: 0;
          bottom: 0;
          line-height: 14px;
          color: $grey;
          white-space: nowrap;
          padding: 2px;
        }
      }
      .price {
        text-align: center;
        font-size: 12px;
        padding: 5px 10px;
        color: #333;
      }
    }
  }
  .nomonkey {
    text-align: center;
    h3 {
      color: $tmdark;
      font-size: 20px;
    }
    span {
      font-size: 12px;
      color: $grey;
    }
  }
  .link {
    text-align: center;
    a {
      color: $link;
      font-size: 14px;
    }
  }
  .record-item {
    display: flex;
    .img {
      height: 50px;
      width: 50px;
      margin-right: 10px;
      img {
        width: 100%;
        background-color: #e0e2ff;
      }
    }
    .info {
      height: 50px;
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      white-space: nowrap;
      div {
        display: flex;
        justify-content: space-between;
      }
      .id {
        font-size: 14px;
      }
      .status {
        font-size: 14px;
      }
      .cost {
        font-size: 10px;
        color: $gray;
      }
      .date {
        font-size: 10px;
        color: $grey;
      }
    }
  }
  .tab {
    width: 200px;
    height: 25px;
    border: 1px solid $tmdark;
    display: flex;
    margin: 0 auto 10px;
    border-radius: 4px;
    font-size: 12px;
    div {
      height: 100%;
      width: 100px;
      line-height: 23px;
      text-align: center;
      cursor: pointer;
    }
    .active {
      background-color: $tmdark;
      color: #fff;
    }
  }
  .load {
    text-align: center;
    font-style: 14px;
  }
  .filters {
    overflow: hidden;
    background: #fbf9fe;
    &::-webkit-scrollbar {
      display: none;
    }
    .wrap {
      padding-bottom: 60px;
      height: 100%;
      overflow-y: scroll;
      padding: 12px;
    }
    .button {
      position: absolute;
      left: 0;
      bottom: 0;
      width: 100%;
      display: flex;
      .btn {
        width: 50%;
        height: 40px;
        margin: 0;
        border: 0;
        border-radius: 0;
        &:after {
          display: none;
        }
      }
    }
  }
</style>

<style lang="scss">
  .input-range {
    .weui-cells {
      display: flex;
      &:before {
        display: none;
      }
      &:after {
        display: none;
      }
      .weui-cell {
        background: #eeeff1;
        padding: 5px 10px;
        border-radius: 5px;
        &:before {
          display: none;
        }
        input {
          text-align: center;
        }
      }
    }
    .weui-cells__title {
      padding-left: 0;
      color: #666;
      font-weight: 500;
    }
    .dash {
      // width: 80px;
      padding: 0 5px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fbf9fe;
      &:before {
        content: '';
        width: 20px;
        height: 1px;
        background: #000;
      }
    }
  }
</style>
